package com.vdong.common.oauth.common.authorize;

import com.vdong.common.oauth.common.authorize.util.JwtTokenUtil;
import com.vdong.common.oauth.common.authorize.util.WebUtils;
import com.vdong.kpay.basics.dubbo.result.APIResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 刀锋
 * @date : Create in 9:31 2018/6/27
 * @description:
 */
@Component
public class AuthAuthenticationSuccessHandler extends
        SimpleUrlAuthenticationSuccessHandler {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        SecurityContext context = SecurityContextHolder.getContext();
        String token = "";
        try {
            if(null != context){
                token = jwtTokenUtil.generateToken();
                logger.debug("login token is " + token);
            }
        } catch (Exception e) {
            logger.error("未登录");
        }
        APIResult<Object> result = new APIResult<>(true);
        result.data(token);
        WebUtils.responseJson(response, result);
    }
}
